package org.springframework.beans.factory.support;

import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.core.SimpleAliasRegistry;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Generic registry for shared bean instances, implementing the
 * {@link org.springframework.beans.factory.config.SingletonBeanRegistry}.
 * Allows for registering singleton instances that should be shared
 * for all callers of the registry, to be obtained via bean name.
 *
 * <p>Also supports registration of
 * {@link org.springframework.beans.factory.DisposableBean} instances,
 * (which might or might not correspond to registered singletons),
 * to be destroyed on shutdown of the registry. Dependencies between
 * beans can be registered to enforce an appropriate shutdown order.
 *
 * <p>This class mainly serves as base class for
 * {@link org.springframework.beans.factory.BeanFactory} implementations,
 * factoring out the common management of singleton bean instances. Note that
 * the {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
 * interface extends the {@link SingletonBeanRegistry} interface.
 *
 * <p>Note that this class assumes neither a bean definition concept
 * nor a specific creation process for bean instances, in contrast to
 * {@link AbstractBeanFactory} and {@link DefaultListableBeanFactory}
 * (which inherit from it). Can alternatively also be used as a nested
 * helper to delegate to.
 *
 * @see org.springframework.beans.factory.DisposableBean
 * @see org.springframework.beans.factory.config.ConfigurableBeanFactory
 * @since 2.0
 */

/**
 * 进行单列bean的注册以及管理，（原型bean的循环依赖不能通过该方法解决，原型bean不放缓存）
 * 一个bean同一时间，只会存在一个缓存中
 */
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry
{

    /**
     * singletonObjects：一级缓存对象
     * key : beanName
     * value : 已经完成实例化，并且填充好了属性值、初始化的bean对象
     * <p>
     * 一级缓存的数据是在什么时候有的呢？
     * 完全完成bean的创建三部曲过程后，才会将 bean的实例，放入一级缓存
     * 一级缓存中的数据是什么时候没有呢？
     * 容器关闭或者应用停止的时候，一级缓存销毁
     */
    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

    /**
     * 二级缓存对象
     * key : beanName
     * value : 只完成了实例化，未完成属性填充和初始化的bean
     * <p>
     * 二级缓存的数据是什么时候有的呢？
     * 第一次从三级缓存中获取对象实例的时候，讲获取到的对象放入二级缓存中
     * 二级缓存中的数据是什么时候没有呢？
     * 完全完成bean的创建三部曲过程后，才会将 bean的实例，放入一级缓存，删除二级缓存
     */
    private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);

    /**
     * 三级缓存
     * key : beanName
     * value : 可以提前暴露 实例化的bean对象 的对象
     * <p>
     * 三级缓存的数据是什么时候有的呢？
     * 当完成了bean的实例化之后，放入三级缓存中
     * 三级缓存中的数据是什么时候没有呢？
     * 第一次从三级缓存中获取对象实例，讲获取到的对象bean放入二级缓存中，同时删除三级缓存的内容
     */
    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

    /**
     * 单利bean对象的beanName存储集合
     */
    private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

    /**
     * 正在注册的单例bean的beanName，避免出现多次初始化，是一个线程安全的set
     */
    private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<>(16));

    /**
     * set集合来存储创建中的bean，是一个线程安全的set
     */
    private final Set<String> inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>(16));

    /**
     * List of suppressed Exceptions, available for associating related causes.
     */
    @Nullable
    private Set<Exception> suppressedExceptions;

    /**
     * Flag that indicates whether we're currently within destroySingletons.
     */
    private boolean singletonsCurrentlyInDestruction = false;

    /**
     * Disposable bean instances: bean name to disposable instance.
     */
    private final Map<String, Object> disposableBeans = new LinkedHashMap<>();

    /**
     * Map between containing bean names: bean name to Set of bean names that the bean contains.
     */
    private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);

    /**
     * Map between dependent bean names: bean name to Set of dependent bean names.
     */
    private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);

    /**
     * Map between depending bean names: bean name to Set of bean names for the bean's dependencies.
     */
    private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);

    @Override
    public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException
    {
        Assert.notNull(beanName, "Bean name must not be null");
        Assert.notNull(singletonObject, "Singleton object must not be null");
        synchronized (this.singletonObjects)
        {
            Object oldObject = this.singletonObjects.get(beanName);
            if (oldObject != null)
            {
                throw new IllegalStateException(
                        "Could not register object [" + singletonObject + "] under bean name '" + beanName +
                                "': there is already object [" + oldObject + "] " + "bound");
            }
            addSingleton(beanName, singletonObject);
        }
    }

    /**
     * Add the given singleton object to the singleton cache of this factory.
     * <p>To be called for eager registration of singletons.
     *
     * @param beanName        the name of the bean
     * @param singletonObject the singleton object
     */
    /**
     * 把对象加到一级缓存中，并且移出二级，三级缓存
     *
     * @param beanName
     * @param singletonObject
     */
    @SuppressWarnings("WeakerAccess")
    protected void addSingleton(String beanName, Object singletonObject)
    {
        synchronized (this.singletonObjects)
        {
            this.singletonObjects.put(beanName, singletonObject);
            this.singletonFactories.remove(beanName);
            this.earlySingletonObjects.remove(beanName);
            // 用来记录保存已经处理好的 bean
            this.registeredSingletons.add(beanName);
        }
    }

    /**
     * Add the given singleton factory for building the specified singleton
     * if necessary.
     * <p>To be called for eager registration of singletons, e.g. to be able to
     * resolve circular references.
     *
     * @param beanName         the name of the bean
     * @param singletonFactory the factory for the singleton object
     */
    /**
     * 该方法会在 doCreateBean()方法执行的时候被调用
     *
     * @param beanName
     * @param singletonFactory
     */
    @SuppressWarnings("WeakerAccess")
    protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory)
    {
        Assert.notNull(singletonFactory, "Singleton factory must not be null");
        synchronized (this.singletonObjects)
        {
            if (!this.singletonObjects.containsKey(beanName))
            {
                this.singletonFactories.put(beanName, singletonFactory);
                this.earlySingletonObjects.remove(beanName);
                this.registeredSingletons.add(beanName);
            }
        }
    }

    @Override
    @Nullable
    public Object getSingleton(String beanName)
    {
        return getSingleton(beanName, true);
    }

    /**
     * Return the (raw) singleton object registered under the given name.
     * <p>Checks already instantiated singletons and also allows for an early
     * reference to a currently created singleton (resolving a circular reference).
     *
     * @param beanName            the name of the bean to look for
     * @param allowEarlyReference whether early references should be created or not
     * @return the registered singleton object, or {@code null} if none found
     */
    /**
     * spring 的二级缓存就已经能够解决循环依赖的问题，但是扩展性不好
     * 三级缓存 getEarlyBeanReference()经过一系列的后置处理来给早期的对象进行特殊化处理
     * 但是 spring 的后置处理器没有经过处理，而是留着开发人员扩展
     */
    /**
     * 单例在Spring的同- - 个容器内只会被创建一次， 后续再获取bean,就直接从单例缓存中获取了。
     * 当然这里也只是尝试加载，首先尝试从缓存中加载，如果加载不成功则再次尝试从singletonFactories中加载。
     * 因为在创建单例bean的时候会存在依赖注人的情况，而在创建依赖单例在Spring的同一个容器内只会被创建一次，
     * 后续再获取bean,就直接从单例缓存中获取了。当然这里也只是尝试加载，首先尝试从缓存中加载，如果加载不成功则再次尝试从
     * singletonFactories中加载。因为在创建单例bean的时候会存在依赖注人的情况，而在创建依赖
     * 的时候为了避免循环依赖,在Spring中创建bean的原则是不等bean创建完成就会将创建bean .
     * 的ObjectFactory提早曝光加入到缓存中,一且下一个bean创建时候需要依赖上一个bean则直
     * 接使用ObjectFactory。
     */
    @Nullable
    @SuppressWarnings("WeakerAccess")
    protected Object getSingleton(String beanName, boolean allowEarlyReference)
    {
        /**
         * 第一步：先尝试去一级缓存（单例缓存池中去获取对象，一般情况从该 map 中获取的对象是可以直接使用）
         * IOC 容器初始化加载单例 Bean 的时候第一次进来，该 map 一般为空
         */
        Object singletonObject = this.singletonObjects.get(beanName);
        /**
         * 若一级缓存中没有获取到对象，并且 singletonCurrentlyInCreation(正在创建)这个 list 包含 beanName
         * IOC 容器初始化加载单例 bean 的时候第一次进来，该 list 一般也为空，但是处理循环依赖的时候，该条件满足
         */
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName))
        {
            synchronized (this.singletonObjects)
            {
                /**
                 * 尝试去二级缓存中获取对象（二级缓存中的对象是一个早期对象）
                 * 早期对象：bean 已经实例化了，但是还未给属性赋值
                 */
                singletonObject = this.earlySingletonObjects.get(beanName);
                /**
                 * 二级缓存中也没有获取到该对象
                 */
                if (singletonObject == null && allowEarlyReference)
                {
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null)
                    {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }

    /**
     * Return the (raw) singleton object registered under the given name,
     * creating and registering a new one if none registered yet.
     *
     * @param beanName         the name of the bean
     * @param singletonFactory the ObjectFactory to lazily create the singleton
     *                         with, if necessary
     * @return the registered singleton object
     */
    @SuppressWarnings("WeakerAccess")
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory)
    {
        Assert.notNull(beanName, "Bean name must not be null");
        synchronized (this.singletonObjects)
        {
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null)
            {
                if (this.singletonsCurrentlyInDestruction)
                {
                    throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed");
                }
                // todo 创建 bean 之前，设置一个创建bean的标识，把该 bean 放入正在创建列表中，防止被多次创建
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                if (this.suppressedExceptions == null)
                {
                    this.suppressedExceptions = new LinkedHashSet<>();
                }
                try
                {
                    // todo 调用匿名内部类，其实就是调用 createBean()方法 创建 bean
                    singletonObject = singletonFactory.getObject();
                    // todo 通过 createBean()方法 创建 bean 则认为是新创建的单例 bean，会在最后把该 bean 放入一级缓存中
                    newSingleton = true;
                }
                catch (IllegalStateException ex)
                {
                    // Has the singleton object implicitly appeared in the meantime ->
                    // if yes, proceed with it since the exception indicates that state.
                    singletonObject = this.singletonObjects.get(beanName);
                    if (singletonObject == null)
                    {
                        throw ex;
                    }
                }
                finally
                {
                    // todo 创建完成bean之后，把该正在创建bean的标识删除
                    afterSingletonCreation(beanName);
                }
                if (newSingleton)
                {
                    // todo 将产生的单列bean，放入一级缓存中
                    addSingleton(beanName, singletonObject);
                }
            }
            return singletonObject;
        }
    }

    /**
     * Register an Exception that happened to get suppressed during the creation of a
     * singleton bean instance, e.g. a temporary circular reference resolution problem.
     *
     * @param ex the Exception to register
     */
    protected void onSuppressedException(Exception ex)
    {
        synchronized (this.singletonObjects)
        {
            if (this.suppressedExceptions != null)
            {
                this.suppressedExceptions.add(ex);
            }
        }
    }

    /**
     * Remove the bean with the given name from the singleton cache of this factory,
     * to be able to clean up eager registration of a singleton if creation failed.
     *
     * @param beanName the name of the bean
     * @see #getSingletonMutex()
     */
    protected void removeSingleton(String beanName)
    {
        synchronized (this.singletonObjects)
        {
            this.singletonObjects.remove(beanName);
            this.singletonFactories.remove(beanName);
            this.earlySingletonObjects.remove(beanName);
            this.registeredSingletons.remove(beanName);
        }
    }

    @Override
    public boolean containsSingleton(String beanName)
    {
        return this.singletonObjects.containsKey(beanName);
    }

    @Override
    public String[] getSingletonNames()
    {
        synchronized (this.singletonObjects)
        {
            return StringUtils.toStringArray(this.registeredSingletons);
        }
    }

    @Override
    public int getSingletonCount()
    {
        synchronized (this.singletonObjects)
        {
            return this.registeredSingletons.size();
        }
    }

    public void setCurrentlyInCreation(String beanName, boolean inCreation)
    {
        Assert.notNull(beanName, "Bean name must not be null");
        if (!inCreation)
        {
            this.inCreationCheckExclusions.add(beanName);
        }
        else
        {
            this.inCreationCheckExclusions.remove(beanName);
        }
    }

    public boolean isCurrentlyInCreation(String beanName)
    {
        Assert.notNull(beanName, "Bean name must not be null");
        return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
    }

    protected boolean isActuallyInCreation(String beanName)
    {
        return isSingletonCurrentlyInCreation(beanName);
    }

    /**
     * Return whether the specified singleton bean is currently in creation
     * (within the entire factory).
     *
     * @param beanName the name of the bean
     */
    public boolean isSingletonCurrentlyInCreation(String beanName)
    {
        return this.singletonsCurrentlyInCreation.contains(beanName);
    }

    /**
     * 把正在加载创建的bean记录在缓存中，方便对循环依赖做检验
     */
    @SuppressWarnings("WeakerAccess")
    protected void beforeSingletonCreation(String beanName)
    {
        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName))
        {
            throw new BeanCurrentlyInCreationException(beanName);
        }
    }

    /**
     * Callback after singleton creation.
     * <p>The default implementation marks the singleton as not in creation anymore.
     *
     * @param beanName the name of the singleton that has been created
     * @see #isSingletonCurrentlyInCreation
     */
    protected void afterSingletonCreation(String beanName)
    {
        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName))
        {
            throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
        }
    }

    /**
     * Add the given bean to the list of disposable beans in this registry.
     * <p>Disposable beans usually correspond to registered singletons,
     * matching the bean name but potentially being a different instance
     * (for example, a DisposableBean adapter for a singleton that does not
     * naturally implement Spring's DisposableBean interface).
     *
     * @param beanName the name of the bean
     * @param bean     the bean instance
     */
    public void registerDisposableBean(String beanName, DisposableBean bean)
    {
        synchronized (this.disposableBeans)
        {
            this.disposableBeans.put(beanName, bean);
        }
    }

    /**
     * Register a containment relationship between two beans,
     * e.g. between an inner bean and its containing outer bean.
     * <p>Also registers the containing bean as dependent on the contained bean
     * in terms of destruction order.
     *
     * @param containedBeanName  the name of the contained (inner) bean
     * @param containingBeanName the name of the containing (outer) bean
     * @see #registerDependentBean
     */
    public void registerContainedBean(String containedBeanName, String containingBeanName)
    {
        synchronized (this.containedBeanMap)
        {
            Set<String> containedBeans =
                    this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8));
            if (!containedBeans.add(containedBeanName))
            {
                return;
            }
        }
        registerDependentBean(containedBeanName, containingBeanName);
    }

    /**
     * Register a dependent bean for the given bean,
     * to be destroyed before the given bean is destroyed.
     *
     * @param beanName          the name of the bean
     * @param dependentBeanName the name of the dependent bean
     */
    public void registerDependentBean(String beanName, String dependentBeanName)
    {
        String canonicalName = canonicalName(beanName);

        synchronized (this.dependentBeanMap)
        {
            Set<String> dependentBeans =
                    this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
            if (!dependentBeans.add(dependentBeanName))
            {
                return;
            }
        }

        synchronized (this.dependenciesForBeanMap)
        {
            Set<String> dependenciesForBean =
                    this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
            dependenciesForBean.add(canonicalName);
        }
    }

    /**
     * Determine whether the specified dependent bean has been registered as
     * dependent on the given bean or on any of its transitive dependencies.
     *
     * @param beanName          the name of the bean to check
     * @param dependentBeanName the name of the dependent bean
     * @since 4.0
     */
    protected boolean isDependent(String beanName, String dependentBeanName)
    {
        synchronized (this.dependentBeanMap)
        {
            return isDependent(beanName, dependentBeanName, null);
        }
    }

    private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen)
    {
        if (alreadySeen != null && alreadySeen.contains(beanName))
        {
            return false;
        }
        String canonicalName = canonicalName(beanName);
        Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
        if (dependentBeans == null)
        {
            return false;
        }
        if (dependentBeans.contains(dependentBeanName))
        {
            return true;
        }
        for (String transitiveDependency : dependentBeans)
        {
            if (alreadySeen == null)
            {
                alreadySeen = new HashSet<>();
            }
            alreadySeen.add(beanName);
            if (isDependent(transitiveDependency, dependentBeanName, alreadySeen))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * Determine whether a dependent bean has been registered for the given name.
     *
     * @param beanName the name of the bean to check
     */
    protected boolean hasDependentBean(String beanName)
    {
        return this.dependentBeanMap.containsKey(beanName);
    }

    /**
     * Return the names of all beans which depend on the specified bean, if any.
     *
     * @param beanName the name of the bean
     * @return the array of dependent bean names, or an empty array if none
     */
    public String[] getDependentBeans(String beanName)
    {
        Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
        if (dependentBeans == null)
        {
            return new String[0];
        }
        synchronized (this.dependentBeanMap)
        {
            return StringUtils.toStringArray(dependentBeans);
        }
    }

    /**
     * Return the names of all beans that the specified bean depends on, if any.
     *
     * @param beanName the name of the bean
     * @return the array of names of beans which the bean depends on,
     * or an empty array if none
     */
    public String[] getDependenciesForBean(String beanName)
    {
        Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
        if (dependenciesForBean == null)
        {
            return new String[0];
        }
        synchronized (this.dependenciesForBeanMap)
        {
            return StringUtils.toStringArray(dependenciesForBean);
        }
    }

    public void destroySingletons()
    {
        if (logger.isTraceEnabled())
        {
            logger.trace("Destroying singletons in " + this);
        }
        synchronized (this.singletonObjects)
        {
            this.singletonsCurrentlyInDestruction = true;
        }

        String[] disposableBeanNames;
        synchronized (this.disposableBeans)
        {
            disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
        }
        for (int i = disposableBeanNames.length - 1; i >= 0; i--)
        {
            destroySingleton(disposableBeanNames[i]);
        }

        this.containedBeanMap.clear();
        this.dependentBeanMap.clear();
        this.dependenciesForBeanMap.clear();

        clearSingletonCache();
    }

    /**
     * Clear all cached singleton instances in this registry.
     *
     * @since 4.3.15
     */
    protected void clearSingletonCache()
    {
        synchronized (this.singletonObjects)
        {
            this.singletonObjects.clear();
            this.singletonFactories.clear();
            this.earlySingletonObjects.clear();
            this.registeredSingletons.clear();
            this.singletonsCurrentlyInDestruction = false;
        }
    }

    /**
     * Destroy the given bean. Delegates to {@code destroyBean}
     * if a corresponding disposable bean instance is found.
     *
     * @param beanName the name of the bean
     * @see #destroyBean
     */
    public void destroySingleton(String beanName)
    {
        // Remove a registered singleton of the given name, if any.
        removeSingleton(beanName);

        // Destroy the corresponding DisposableBean instance.
        DisposableBean disposableBean;
        synchronized (this.disposableBeans)
        {
            disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
        }
        destroyBean(beanName, disposableBean);
    }

    /**
     * Destroy the given bean. Must destroy beans that depend on the given
     * bean before the bean itself. Should not throw any exceptions.
     *
     * @param beanName the name of the bean
     * @param bean     the bean instance to destroy
     */
    protected void destroyBean(String beanName, @Nullable DisposableBean bean)
    {
        // Trigger destruction of dependent beans first...
        Set<String> dependencies;
        synchronized (this.dependentBeanMap)
        {
            // Within full synchronization in order to guarantee a disconnected Set
            dependencies = this.dependentBeanMap.remove(beanName);
        }
        if (dependencies != null)
        {
            if (logger.isTraceEnabled())
            {
                logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
            }
            for (String dependentBeanName : dependencies)
            {
                destroySingleton(dependentBeanName);
            }
        }

        // Actually destroy the bean now...
        if (bean != null)
        {
            try
            {
                bean.destroy();
            }
            catch (Throwable ex)
            {
                if (logger.isWarnEnabled())
                {
                    logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
                }
            }
        }

        // Trigger destruction of contained beans...
        Set<String> containedBeans;
        synchronized (this.containedBeanMap)
        {
            // Within full synchronization in order to guarantee a disconnected Set
            containedBeans = this.containedBeanMap.remove(beanName);
        }
        if (containedBeans != null)
        {
            for (String containedBeanName : containedBeans)
            {
                destroySingleton(containedBeanName);
            }
        }

        // Remove destroyed bean from other beans' dependencies.
        synchronized (this.dependentBeanMap)
        {
            for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it
                    .hasNext(); )
            {
                Map.Entry<String, Set<String>> entry = it.next();
                Set<String> dependenciesToClean = entry.getValue();
                dependenciesToClean.remove(beanName);
                if (dependenciesToClean.isEmpty())
                {
                    it.remove();
                }
            }
        }

        // Remove destroyed bean's prepared dependency information.
        this.dependenciesForBeanMap.remove(beanName);
    }

    /**
     * Exposes the singleton mutex to subclasses and external collaborators.
     * <p>Subclasses should synchronize on the given Object if they perform
     * any sort of extended singleton creation phase. In particular, subclasses
     * should <i>not</i> have their own mutexes involved in singleton creation,
     * to avoid the potential for deadlocks in lazy-init situations.
     */
    @Override
    public final Object getSingletonMutex()
    {
        return this.singletonObjects;
    }

}
